<?php

class ChoiceForm extends BaseForm {
  const FORM_NAME           = 'frm';

  const FIELD_QUESTION    = 'question';
  const FIELD_CHOICE      = 'choice';
  const FIELD_IS_CORRECT  = 'is_correct';

  public function configure() {
    $arrIsCorrect     = array( Constants::STATUS_INACTIVE => 'No', Constants::STATUS_ACTIVE => 'Yes');
    $arrQuestionList  = QUESTIONTable::getInstance()->getArrayGroupByCourseId();

    $widget = array(
            self::FIELD_QUESTION      => new sfWidgetFormSelect(array('choices' => $arrQuestionList), array('multiple' => false, 'expand' => true)),
            self::FIELD_CHOICE    => new sfWidgetFormInputText(array(), array('maxlength' => 255)),
            self::FIELD_IS_CORRECT  => new sfWidgetFormChoice(array('choices' => $arrIsCorrect))
    );

    $labels = array(
            self::FIELD_QUESTION   => 'Question<req />',
            self::FIELD_CHOICE    => 'Choice<req />',
            self::FIELD_IS_CORRECT         => 'Is Correct<req />'
    );

    $this->setWidgets($widget);
    $this->widgetSchema->setLabels($labels);

    $validators = array(
            self::FIELD_QUESTION   => new sfValidatorString(array('trim' => true), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_QUESTION])))),
            self::FIELD_CHOICE   => new sfValidatorString(array('trim' => true), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_CHOICE])))),
            self::FIELD_IS_CORRECT      => new sfValidatorString(array('trim' => true), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_IS_CORRECT]))))
    );

    $this->setValidators($validators);
    $this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'postValidator'))));

    $this->widgetSchema->setNameFormat(self::FORM_NAME . '[%s]');

    $this->validatorSchema->setOption('allow_extra_fields', true);
    $this->validatorSchema->setOption('filter_extra_fields', false);
  }

  public function postValidator($validator, $values) {
    $isCorrectExist = CHOICETable::getInstance()->isCorrectExist($values[self::FIELD_QUESTION]);
    if ($isCorrectExist && $values[self::FIELD_IS_CORRECT] == Constants::STATUS_ACTIVE) {
      throw new sfValidatorErrorSchema($validator, array(self::FIELD_IS_CORRECT => new sfValidatorError($validator, LangUtil::getText('error_correct_exist')) ));
    }
    return $values;
  }

  public function populateData(CHOICE $choice) {
    $this->setDefault(self::FIELD_CHOICE, $choice->getChoice());
    $this->setDefault(self::FIELD_QUESTION, $choice->getQuestionId());
    $this->setDefault(self::FIELD_IS_CORRECT, $choice->getIsCorrect());
  }
}
?>